package com.caipos.akka;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * Akka初始化器，在Spring上下文完全刷新后才创建Actor
 */
@Component
public class AkkaActorInitializer implements ApplicationListener<ContextRefreshedEvent> {

    private ActorSystem actorSystem;
    private ActorRef deviceManagerActor;
    private ActorRef dataProcessingActor;

    // 标记是否已初始化
    private boolean initialized = false;

    /**
     * 当Spring上下文完全刷新后（所有Bean都已初始化），才创建Actor系统
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 防止重复初始化（Spring可能会触发多次ContextRefreshedEvent）
        if (!initialized) {
            // 创建Actor系统
            actorSystem = ActorSystem.create("CaiposIoTSystem");

            // 创建数据处理Actor
            dataProcessingActor = actorSystem.actorOf(DataProcessingActor.props(), "dataProcessingActor");

            // 创建设备管理器Actor
            deviceManagerActor = actorSystem.actorOf(
                    DeviceManagerActor.props(dataProcessingActor),
                    "deviceManagerActor"
            );

            initialized = true;
        }
    }

    /**
     * 应用关闭时，优雅关闭Actor系统
     */
    public void shutdown() {
        if (actorSystem != null) {
            actorSystem.terminate();
        }
    }

    // Getters
    public ActorSystem getActorSystem() {
        return actorSystem;
    }

    public ActorRef getDeviceManagerActor() {
        return deviceManagerActor;
    }

    public ActorRef getDataProcessingActor() {
        return dataProcessingActor;
    }
}
    